#!/bin/sh
#
# Perform necessary datadog-agent setup steps prior to remove the old package.
#
# .deb: STEP 1 of 5

INSTALL_DIR=/opt/datadog-agent
SERVICE_NAME=datadog-agent

stop_agent()
{
    # Stop an already running agent
    # supports systemd, upstart and sysvinit
    if command -v systemctl >/dev/null 2>&1; then
        systemctl stop $SERVICE_NAME-process || true
        systemctl stop $SERVICE_NAME-sysprobe || true
        systemctl stop $SERVICE_NAME-trace || true
        systemctl stop $SERVICE_NAME-security || true
        systemctl stop $SERVICE_NAME || true
    elif command -v initctl >/dev/null 2>&1; then
        initctl stop $SERVICE_NAME-process || true
        initctl stop $SERVICE_NAME-sysprobe || true
        initctl stop $SERVICE_NAME-trace || true
        initctl stop $SERVICE_NAME-security || true
        initctl stop $SERVICE_NAME || true
    elif command -v service >/dev/null 2>&1; then
        service $SERVICE_NAME-process stop || true
        # TODO: investigate if the following line could be used in other cases than with sysvinit systems (which don't support sysprobe).
        # If not, remove it.
        service $SERVICE_NAME-sysprobe stop || true
        service $SERVICE_NAME-trace stop || true
        service $SERVICE_NAME-security stop || true
        service $SERVICE_NAME stop || true
    else
        echo "[ WARNING ]\tCannot detect a supported init system. The datadog-agent package only provides service files for systemd, upstart and sysvinit."
    fi
}

deregister_agent()
{
    # Disable agent start on system boot
    # supports systemd, upstart and sysvinit
    if command -v systemctl >/dev/null 2>&1; then
        # Force systemd to ignore the sysvinit scripts. Only cosmetic, remove some irrelevant warnings during upgrade
        SYSTEMCTL_SKIP_SYSV=true systemctl disable $SERVICE_NAME-process || true
        SYSTEMCTL_SKIP_SYSV=true systemctl disable $SERVICE_NAME-sysprobe || true
        SYSTEMCTL_SKIP_SYSV=true systemctl disable $SERVICE_NAME-trace || true
        SYSTEMCTL_SKIP_SYSV=true systemctl disable $SERVICE_NAME-security || true
        SYSTEMCTL_SKIP_SYSV=true systemctl disable $SERVICE_NAME || true
    elif command -v initctl >/dev/null 2>&1; then
        # Nothing to do, this is defined directly in the upstart job file
        :
    elif command -v update-rc.d >/dev/null 2>&1; then
        update-rc.d -f $SERVICE_NAME-process remove || true
        # TODO: investigate if the following line could be used in other cases than with sysvinit systems (which don't support sysprobe).
        # If not, remove it.
        update-rc.d -f $SERVICE_NAME-sysprobe remove || true
        update-rc.d -f $SERVICE_NAME-trace remove || true
        update-rc.d -f $SERVICE_NAME-security remove || true
        update-rc.d -f $SERVICE_NAME remove || true
    else
        echo "[ WARNING ]\tCannot detect a supported init system. The datadog-agent package only provides service files for systemd, upstart and sysvinit."
    fi
}

remove_py_compiled_files()
{
    # Delete all the .pyc files in the embedded dir that are part of the agent's package
    # This MUST be done after using pip or any python, because executing python might generate .pyc files
    if [ -f "$INSTALL_DIR/embedded/.py_compiled_files.txt" ]; then
        # (commented lines are filtered out)
        cat $INSTALL_DIR/embedded/.py_compiled_files.txt | grep -v '^#' | xargs rm -f
    fi
}

remove_custom_integrations()
{
    # Since 6.18.0, a file containing all integrations files which have been installed by
    # the package is available. We use it to remove only the datadog-related check files which
    # have *NOT* been installed by the package (eg: installed using the `integration` command).

    if [ -f "$INSTALL_DIR/embedded/.installed_by_pkg.txt" ]; then
        echo "Removing integrations installed with the 'agent integration' command"

        # List all files in the embedded dir of the datadog-agent install dir
        PREV_DIR=$(pwd)
        cd "$INSTALL_DIR" || return
        find . -depth -path './embedded/lib/python*/site-packages/datadog_*' > $INSTALL_DIR/embedded/.all-integrations.txt

        # List all files in the embedded dir of the datadog-agent install dir
        # which were not installed by the package and rm them.
        grep -Fxv -f $INSTALL_DIR/embedded/.installed_by_pkg.txt $INSTALL_DIR/embedded/.all-integrations.txt | grep -v '^#' | xargs --no-run-if-empty -I '{}' rm -r $INSTALL_DIR/{}

        rm $INSTALL_DIR/embedded/.all-integrations.txt
        cd "$PREV_DIR" || return
    fi
}

remove_version_history()
{
    # Since 6.22.0/7.22.0, a file containing the version history of the currently installed
    # Agent is created (by default in /opt/datadog-agent/run). On a full uninstall, remove this
    # file.
    # This is a best-effort solution, as users can decide to put this file in another place
    # by changing the logs_config.run_path value.

    if [ -f "$INSTALL_DIR/run/version-history.json" ]; then
        echo "Removing version history file"
        rm "$INSTALL_DIR/run/version-history.json" || true
    fi
}

remove_sysprobe_secagent_files()
{
    # removing sbom files and dirs
    find "$INSTALL_DIR/run" -name "sbom*" -type d -exec rm -r {} +

    # removing security profiles
    find "$INSTALL_DIR/run/runtime-security/profiles" -delete || true

    # remove other runtime files
    for file in run/runtime-security-registry.json run/compliance-registry.json run/sysprobe.sock run/event-monitor.sock run/runtime-security.sock run/system-probe.pid run/runtime-security
    do
        if [ -d "$INSTALL_DIR/$file" ]; then
            rmdir "$INSTALL_DIR/$file" 2>/dev/null || true
        elif [ -e "$INSTALL_DIR/$file" ]; then
            rm "$INSTALL_DIR/$file" || true
        fi
    done

    if [ -d "$INSTALL_DIR/run" ]; then
        rmdir "$INSTALL_DIR/run" 2>/dev/null || true
    fi
}

remove_remote_config_db()
{
    # Remote config stores a cache of the current repository state in
    # /opt/datadog-agent/run. This is a best-effort solution, as users can
    # decide to put this file in another place by changing the top-level
    # run_path config value.
    if [ -f "$INSTALL_DIR/run/remote-config.db" ]; then
        echo "Removing remote configuration config database"
        rm "$INSTALL_DIR/run/remote-config.db" || true
    fi
}

stop_agent
deregister_agent
remove_custom_integrations
remove_py_compiled_files

case "$1" in
    remove)
        # We're uninstalling.
        remove_version_history
        remove_sysprobe_secagent_files
        remove_remote_config_db
    ;;
    upgrade)
        # We're upgrading.
    ;;
    *)
    ;;
esac

# Delete all .pyc files in the `agent/` and the `bin/agent/dist` dirs
find $INSTALL_DIR/bin/agent/dist -name '*.py[co]' -type f -delete || echo "Unable to delete .pyc files in $INSTALL_DIR/bin/agent/dist"
find $INSTALL_DIR/bin/agent/dist -name '__pycache__' -type d -delete || echo "Unable to delete __pycache__ directories in $INSTALL_DIR/bin/agent/dist"

exit 0
